<?php
class Admin_CruiseItineraryTourController extends Apps_Controller_Action_Admin {
	//LIST
	public function indexAction() {
		$this->actResolve('act_delete',
						  'delete', null, null, array('id' => $this->_getParam('item_checker')),
					 	  true);

		$tbCruiseItineraryTour = new M_DbTable_CruiseItineraryTour();
		$grid 	= new Apps_Plugin_Grid('cruiseGrid');

		$grid->setData($tbCruiseItineraryTour->getList())
			 ->setTableCaption('Cruise - Tour')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Cruise',
			 			  'dataField'	=> 'en_name'),
			 		array('title'		=> 'Itinerary',
			 			  'dataField'	=> 'cruise_itinerary_en_code',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Title',
			 			  'dataField'	=> 'en_title',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Promotion',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['special_offer'] == M_DbTable_CruiseItineraryTour::SPECIAL_OFFER_TRUE)
			 			  								? '<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' 
			 			  								: '<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=offer&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Best Selling',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['best_selling'] == M_DbTable_CruiseItineraryTour::BEST_SELLING_TRUE)
			 			  								? '<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=best_selling&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' 
			 			  								: '<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=best_selling&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
                    array('title'		=> 'Public',
			 			  'html'	    => function ($rs) {
			 			  						return ($rs['status'] == M_DbTable_CruiseItineraryTour::STATUS_ACTIVE)
			 			  								? '<a href="##" class="ajax-link-must-confirm popup hint  label label-success" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="No">Yes</a>' 
			 			  								: '<a href="##" class="ajax-link-must-confirm popup hint  label label-warning" data-ajax-to="/admin/cruise-itinerary-tour/change-value?p=public&id=' . $rs['id'] . '" data-must-confirm-msg="Do you want to change this ?" title="Thay đổi" data-after-ajax="Yes">No</a>';
											},
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Photo',
			 			  'width'       => '2%',
			 			  'html'        => array('<a href="/admin/photo-management/cruise?id=%s"><i class="icon-folder-open" title="Quản lý ảnh"></i></a>',
			 			  				   array('id')),
			 			  'class'		=> 'center'),
	 			    array('title'		=> 'View',
	 			  		  'html'        => array('<a href="/cruise/detail?id=%s" target="_blank"><i class="icon-list-alt"></i></a>',
	 			  						   array('id')),
	 			  		  'class'		=> 'center'),
			 		array('title'       => 'Edit',
			 			  'html'        => array('<a href="/admin/cruise-itinerary-tour/edit?id=%s"><i class="icon-edit" title="Sửa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%'),
			 	    array('title'       => 'Delete',
			 			  'html'        => array('<a href="/admin/cruise-itinerary-tour/delete?id=%s" class="must-confirm" data-must-confirm-msg="Bạn có chắc là muốn xóa?"><i class="icon-remove" title="Xóa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%',
	 			  		  'class'		=> 'center')
			 		));
		$grid->applySearch(new Admin_Form_Search_TourCruise());

		$this->view->grid = $grid;
	}

	//ADD
	public function addAction() {
		$rq 		= $this->_request;
		$f 			= new Admin_Form_AddCruiseItineraryTour();
		
		$tbArticle 	= new M_DbTable_Article();
		$tbCruiseItineraryTour	= new M_DbTable_CruiseItineraryTour(); 

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_CRUISE);
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;
				//resize images
				try {
				    $thumbnailNew = str_replace('/cruise/', '/cruise/thumbnail_', $thumbnail);
				    $image = new Apps_Plugin_ResizeImages();
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(156);
				    $image->save(PUBLIC_PATH .$thumbnailNew);

				    //detail thumbnail;
				    $detailThumbnail = str_replace('/cruise/', '/cruise/detail_thumbnail_', $thumbnail);
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(366);
				    $image->save(PUBLIC_PATH .$detailThumbnail);
				} catch (Exception $e) {
				    //Excetion here
				}

				$data = $f->getValues();
				$data['thumbnail'] 		  = $thumbnailNew;
				$data['detail_thumbnail'] = $detailThumbnail;
				
				$keyFilterCruise = array('cruise_id',
									     'cruise_itinerary_id',
									     'special_offer',
									     'best_selling',
				                         'detail_thumbnail',
									   	 'meta_keyword',
									   	 'meta_description',
									     'header_title');

				$cruiseId = $tbCruiseItineraryTour->safelyInsert($data, $keyFilterCruise);

				if ($cruiseId) {
				    //add price table
				    $tbCruiseCabinType      = new M_DbTable_CruiseCabinType();
				    $tbCruiseCabinTypePrice = new M_DbTable_CruiseCabinTypePrice();

				    $cabinType = $rq->getParam('cabin_type');
				    $sgl       = $rq->getParam('sgl');

				    foreach($cabinType as $k => $v) {
				        if($v) {
				            $cruiseCabinType = array('cruise_itinerary_tour_id'   => $cruiseId,
                				                     'cabin_type'   				=> $v,
                				                     'sgl_supp'     				=> $sgl[$k]);

				            $cruiseCabinTypeId = $tbCruiseCabinType->insert($cruiseCabinType);

				            if($cruiseCabinTypeId) {
				                for($i = 0; $i < 5; $i++) {
				                    $price = $rq->getParam('price_'.($i + 1));
				                    $cruiseCabinTypePrice = array('cruise_itinerary_cabin_type_id'  => $cruiseCabinTypeId,
                        				                          'number_customer'        			=> $rq->getParam('number_customer_'.($i + 1)),
                        				                          'price'                  			=> $price[$k]);
				                    $tbCruiseCabinTypePrice->insert($cruiseCabinTypePrice);
				                }
				            }
				        }
				    }
					$this->_flashMessenger->addMessage(
						$tbArticle->addArticle($data, $cruiseId, $tbArticle::REFERENCE_TYPE_CRUISE)
						? self::$msgAddSuccess
						: self::$msgAddFailed
					);
				}
				$this->_helper->redirector('index', null, null);
			}
		}
		$this->view->form = $f;
	}

	//EDIT Cruise
	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		$tbArticle 	= new M_DbTable_Article();
		$tbCruiseItineraryTour 	= new M_DbTable_CruiseItineraryTour();

		$cruiseItineraryTour = $tbCruiseItineraryTour->getCruiseItineraryTour($id);

		if (!$id || !$cruiseItineraryTour) {
			$this->_helper->redirector('index');
		}

		$f = new Admin_Form_AddCruiseItineraryTour();
		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail - replace thumbnail if changed
				$rs = $tbArticle->getArticleByReference($id, $tbArticle::REFERENCE_TYPE_CRUISE)->query()->fetch();
				$thumbnail = $rs['thumbnail'];

				if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_CRUISE);

					$uploaded = $uploader->upload();
					if($uploaded) {
						// Delete ex-thumbnail: có 3 ảnh: 1 ảnh gốc, 2 ảnh resize: thumbnail, detail-thumbnail
						unlink(Apps_Plugin_Upload_File::getPath($thumbnail));
						unlink(Apps_Plugin_Upload_File::getPath(str_replace('/cruise/thumbnail_', '/cruise/', $thumbnail))); // Delete thumbnail
						unlink(Apps_Plugin_Upload_File::getPath(str_replace('/cruise/thumbnail_', '/cruise/detail_thumbnail_', $thumbnail))); // Delete ex-detail thumbnail

						$thumbnail = $uploaded['thumbnail']['uri'];

						//resize images
						try {
        				    $thumbnailNew = str_replace('/cruise/', '/cruise/thumbnail_', $thumbnail);
    						$image = new Apps_Plugin_ResizeImages();
        				    $image->load(PUBLIC_PATH .$thumbnail);
        				    $image->resizeToWidth(156);
        				    $image->save(PUBLIC_PATH .$thumbnailNew);

        				    //detail thumbnail;
        				    $detailThumbnail = str_replace('/cruise/', '/cruise/detail_thumbnail_', $thumbnail);
        				    $image->load(PUBLIC_PATH .$thumbnail);
        				    $image->resizeToWidth(366);
        				    $image->save(PUBLIC_PATH .$detailThumbnail);

						} catch (Exception $e) {
						}
					}
				}

				$data = $f->getValues();
				$data['thumbnail'] = $thumbnail;

				$keyFilterCruise = array('cruise_id',
									     'cruise_itinerary_id',
									     'special_offer',
									     'best_selling',
				                         'detail_thumbnail',
									   	 'meta_keyword',
									   	 'meta_description',
									     'header_title');
				
				$rT = $tbCruiseItineraryTour->safelyUpdate($data, array('id =?' => $id) , $keyFilterCruise);
				$rA = $tbArticle->updateArticle($data, $id, $tbArticle::REFERENCE_TYPE_CRUISE);

			    //to edit price: delete price then add new
			    $tbCruiseCabinType      = new M_DbTable_CruiseCabinType();
			    $tbCruiseCabinType->delete(array('cruise_itinerary_tour_id =?' => $id));
			    //add price table
			    $tbCruiseCabinTypePrice = new M_DbTable_CruiseCabinTypePrice();

			    $cabinType = $rq->getParam('cabin_type');
			    $sgl       = $rq->getParam('sgl');
			    foreach($cabinType as $k => $v) {
			        if($v) {
			            $cruiseCabinType = array('cruise_itinerary_tour_id'   => $id,
            				                     'cabin_type'   				=> $v,
            				                     'sgl_supp'     				=> $sgl[$k]);
			            $cruiseCabinTypeId = $tbCruiseCabinType->insert($cruiseCabinType);
			            if($cruiseCabinTypeId) {
			                for($i = 0; $i < 5; $i++) {
			                    $price = $rq->getParam('price_'.($i + 1));
			                    $cruiseCabinTypePrice = array('cruise_itinerary_cabin_type_id'  => $cruiseCabinTypeId,
                    				                          'number_customer'        			=> $rq->getParam('number_customer_'.($i + 1)),
                    				                          'price'                  			=> $price[$k]);
			                    $tbCruiseCabinTypePrice->insert($cruiseCabinTypePrice);
			                }
			            }
			        }
			    }

				if (!$rT && !$rA) {
					$this->_flashMessenger->addMessage(self::$msgUpdateFailed);
				} else {
					$this->_flashMessenger->addMessage(self::$msgUpdateSuccess);
				}
				$this->_helper->redirector('index');
			}
		}
		//populate price table
		$tbCruiseCabinType      = new M_DbTable_CruiseCabinType();
		$tbCruiseCabinTypePrice = new M_DbTable_CruiseCabinTypePrice();

		$cruiseCabinType = $tbCruiseCabinType->fetchAll(array('cruise_itinerary_tour_id =?' => $id))->toArray();
		foreach($cruiseCabinType as $k => $v) {
		    $cruiseCabinType[$k]['price'] = $tbCruiseCabinTypePrice->fetchAll(array('cruise_itinerary_cabin_type_id =?' => $v['id']))->toArray();
		}
		$this->view->cruiseCabin = $cruiseCabinType;

		$f->setLegend('Update Cruise Tour');
		$f->populate($cruiseItineraryTour->query()->fetch());
		$this->view->form = $f;
		$this->render('add');
	}

	//DELETE
	public function deleteAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');

		if (!$id) {
			$this->_helper->redirector('index');
		}

		$tbArticle = new M_DbTable_Article();
		$tbCruiseItineraryTour = new M_DbTable_CruiseItineraryTour();

		if (is_numeric($id)) {
			if ($tbCruiseItineraryTour->safelyDelete('id ='. $id)) {
				$this->_flashMessenger->addMessage(
					$tbArticle->deleteArticle($id, $tbArticle::REFERENCE_TYPE_CRUISE)
					? self::$msgDeleteSuccess
					: self::$msgDeleteError
				);
			}
		} elseif (is_array($id)) {
			foreach ($id as $v) {
				if ($tbCruiseItineraryTour->safelyDelete('id ='. $v)) {
					$tbArticle->deleteArticle($v, $tbArticle::REFERENCE_TYPE_CRUISE);
				}
			}
		}

		$this->_helper->redirector('index');
	}

	public function changeValueAction() {
		$this->disableLayout(true, true);
		$rq = $this->_request;
		$param  = $rq->getParam('p');
		$id 	= intval($rq->getParam('id'));
		$tbCruiseItineraryTour = new M_DbTable_CruiseItineraryTour();
		
		if(!($r = $tbCruiseItineraryTour->fetchRow(array('id = ?' => $id))->toArray())) {
			echo '<script>window.location=window.location</script>
				<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
				. $this->getBacktrackUrl()
				. '">Update Error (Record not found), please wait ...</a>';
		}

		switch ($param) {
			case 'offer':
				($r['special_offer'] == M_DbTable_CruiseItineraryTour::SPECIAL_OFFER_TRUE) ?
					$tbCruiseItineraryTour->safelyUpdate(array('special_offer' 		=> M_DbTable_CruiseItineraryTour::SPECIAL_OFFER_FALSE),
													     array('id =?'				=> $id)) :
					$tbCruiseItineraryTour->safelyUpdate(array('special_offer' 		=> M_DbTable_CruiseItineraryTour::SPECIAL_OFFER_TRUE),
													     array('id =?'				=> $id));
				break;
				
			case 'best_selling':
				($r['best_selling'] == M_DbTable_CruiseItineraryTour::BEST_SELLING_TRUE) ?
					$tbCruiseItineraryTour->safelyUpdate(array('best_selling' 		=> M_DbTable_CruiseItineraryTour::BEST_SELLING_FALSE),
													     array('id =?'				=> $id)) :
					$tbCruiseItineraryTour->safelyUpdate(array('best_selling' 		=> M_DbTable_CruiseItineraryTour::BEST_SELLING_TRUE),
													     array('id =?'				=> $id));
				break;

			case 'public':
			    ($r['status'] == M_DbTable_CruiseItineraryTour::STATUS_ACTIVE) ?
    			    $tbCruiseItineraryTour->safelyUpdate(array('status'  => M_DbTable_CruiseItineraryTour::STATUS_INACTIVE),
    			                         				 array('id =?'	  => $id)) :
    			    $tbCruiseItineraryTour->safelyUpdate(array('status'  => M_DbTable_CruiseItineraryTour::STATUS_ACTIVE),
    			                        				 array('id =?'  => $id));
			    break;


			default: break;
		}
		echo '<script>location.href = location.href</script>
			<a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
			. $this->getBacktrackUrl()
			. '">Update successfully, please wait ...</a>';
	}
}